package com.example.application61;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nle.mylibrary.claimer.connector.ConnectorListener;
import com.nle.mylibrary.claimer.rfid.SingleEpcListener;
import com.nle.mylibrary.databus.DataBus;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.databus.ReciveData;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.RFID;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView main_tv_chepai;
    private TextView main_tv_enter;
    private TextView main_tv_exit;
    private TextView main_tv_len;
    private TextView main_tv_money;
    private Button main_but_open;
    private DataBus dataBus;
    private TextToSpeech tts;
    private DataBus dataBus1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        main_tv_chepai = findViewById(R.id.main_tv_chepai);
        main_tv_enter = findViewById(R.id.main_tv_enter);
        main_tv_exit = findViewById(R.id.main_tv_exit);
        main_tv_len = findViewById(R.id.main_tv_len);
        main_tv_money = findViewById(R.id.main_tv_money);
        main_but_open = findViewById(R.id.main_but_open);
        main_but_open.setOnClickListener(this);

        main_but_open.setEnabled(false);

//        config = getSharedPreferences("config", MODE_PRIVATE);
//        SharedPreferences.Editor edit = config.edit();
//        edit.putString("E2 80 69 95 00 00 40 12 6C C1 6C C9","end,E2 80 69 95 00 00 40 12 6C C1 6C C9,欢迎入场,甘L 6N666");
//        edit.putString("E2 80 69 95 00 00 40 12 6C C1 48 C9","E2 80 69 95 00 00 40 12 6C C1 48 C9,欢迎入场,甘G 85A69");
//        edit.putString("E2 80 69 95 00 00 50 12 6C C2 40 C9","E2 80 69 95 00 00 50 12 6C C2 40 C9,欢迎入场,甘M 146R8");
//        edit.commit();

        HashMap<String, BaseInfo> objectObjectHashMap = new HashMap<>();

        objectObjectHashMap.put("E2 80 69 95 00 00 40 12 6C C1 6C C9",
                new BaseInfo("E2 80 69 95 00 00 40 12 6C C1 6C C9","欢迎入场","甘L 6N111","","","0"));
        objectObjectHashMap.put("E2 80 69 95 00 00 40 12 6C C1 48 C9",
                new BaseInfo("E2 80 69 95 00 00 40 12 6C C1 48 C9","欢迎入场","甘L 6N222","","","0"));
        objectObjectHashMap.put("E2 80 69 95 00 00 50 12 6C C2 40 C9",
                new BaseInfo("E2 80 69 95 00 00 50 12 6C C2 40 C9","欢迎入场","甘L 6N333","","","0"));


        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

            }
        });
        dataBus = DataBusFactory.newSocketDataBus(Util.ip, Util.port);
        dataBus.setReciveDataListener(new ReciveData() {
            @Override
            public String getReciveData(byte[] bytes) {
                return null;
            }
        });

//        dataBus1 = DataBusFactory.newSocketDataBus(Util.ip1, Util.port1);
//        dataBus1.setReciveDataListener(new ReciveData() {
//            @Override
//            public String getReciveData(byte[] bytes) {
//                return null;
//            }
//        });

//        GenericConnector genericConnector = new GenericConnector(dataBus1,null);

        RFID rfid = new RFID(dataBus, null);

//        try {
//            genericConnector.sendTCPSetDoVlue(2, 2, true, new ConnectorListener() {
//                @Override
//                public void onSuccess(boolean b) {
//                    Log.i("灯",b+"");
//                }
//
//                @Override
//                public void onFail(Exception e) {
//
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        new Thread(){
            @Override
            public void run() {
                super.run();

                System.out.println("***********************");
                while (true){

                    boolean enabled = main_but_open.isEnabled();
                    if(enabled){
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                    try {
                    rfid.readSingleEpc(new SingleEpcListener() {
                        @Override
                        public void onVal(String s) {
                            if (s != null) {

                                BaseInfo baseInfo = objectObjectHashMap.get(s);
                                if (baseInfo == null) {
                                    //objectObjectHashMap.put(s, new BaseInfo(s, "欢迎入场", "甘L 6N60006", "", "", "0"));
                                    objectObjectHashMap.put(s, new BaseInfo(s, "无车辆信息", "", "", "", ""));
                                }
                                if(s.equals(baseInfo)){
                                    objectObjectHashMap.put(s, new BaseInfo(s, "无车辆信息", "", "", "", ""));
                                }
                                baseInfo = objectObjectHashMap.get(s);

                                Log.i("标签号", s);

                                String flag = baseInfo.getFlag();
                                if ("1".equals(flag)) {
                                    //出厂逻辑
                                    String startDate = baseInfo.getStartDate();
                                    String endDate = time();
                                    baseInfo.setEndDate(endDate);
                                    baseInfo.setFlag("0");
                                    //计算金额
                                    int totleTime = jisuanshijian(baseInfo.getStartDate(),endDate);

                                    int v = totleTime / 60;
                                    int v1 = totleTime % 60;

                                    int money = totleTime*10;


                                    tts.speak("一路平安" + baseInfo.getPaihao(), TextToSpeech.QUEUE_FLUSH, null, null);

                                    Message message = new Message();
                                    message.what = 1;

                                    Bundle bundle = new Bundle();
                                    bundle.putString("startDate",startDate);
                                    bundle.putString("endDate", endDate);
                                    bundle.putString("totleTime",v+"时"+v1+"分");
                                    bundle.putString("money",money+"");
                                    bundle.putString("chepai",baseInfo.getPaihao());
                                    message.setData(bundle);

                                    handler.sendMessage(message);


                                } else if ("0".equals(flag)) {
                                    //进场逻辑
                                    //播报语音
                                    tts.speak(baseInfo.getTts() + baseInfo.getPaihao(), TextToSpeech.QUEUE_FLUSH, null, null);
                                    //设置进场时间
                                    baseInfo.setStartDate(time());
                                    baseInfo.setFlag("1");


                                    Message message = new Message();
                                    message.what = 2;

                                    Bundle bundle = new Bundle();
                                    bundle.putString("startDate",baseInfo.getStartDate());
                                    bundle.putString("chepai",baseInfo.getPaihao());
                                    message.setData(bundle);

                                    handler.sendMessage(message);
                                }


                            }
                        }

                        @Override
                        public void onFail(Exception e) {
//                            Log.e("err",e.getMessage() == null?"":e.getMessage());
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }
        }.start();

    }

    private String time() {

        Date date = new Date();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);

        return time;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.main_but_open:

                //打开闸门 开绿灯


                //按钮不可点击
                Button button = (Button) v;
                v.setEnabled(false);
                break;
        }
    }

    private int jisuanshijian(String startDate,String endDate) {
        String exittime = endDate;
        int fen=0;
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date enterstr = simpleDateFormat1.parse(startDate);
            Date exitstr = simpleDateFormat1.parse(exittime);
            String cha = String.valueOf(exitstr.getTime() - enterstr.getTime());
            int ss = Integer.valueOf(cha);
            fen = ss/60000;
            if(ss % 60000 != 0){
                fen = fen + 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return fen;
    }

    Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 1:
                    Bundle data = msg.getData();
                    String chepai = data.getString("chepai");
                    String startDate = data.getString("startDate");
                    String endDate = data.getString("endDate");
                    String totleTime = data.getString("totleTime");
                    String money = data.getString("money");
                    main_tv_chepai.setText(chepai);
                    main_tv_enter.setText(startDate);
                    main_tv_exit.setText(endDate);
                    main_tv_len.setText(totleTime);
                    main_tv_money.setText(money);
                    break;
                case 2:
                    Bundle data1 = msg.getData();
                    String chepai1 = data1.getString("chepai");
                    String startDate1 = data1.getString("startDate");
                    main_tv_chepai.setText(chepai1);
                    main_tv_enter.setText(startDate1);
                    break;
            }
        }
    };

}